import {Form, Select, Spin} from 'antd'
import {compose, withState} from 'recompose'
import {Group} from '../components'

const FormItem = Form.Item;

const Option = Select.Option;


const _SearchInput = (props) => {
    const {mode, value, style, defaultValue, width, onChange, placeholder, state: {fetching, option}, setState, onSearch, options = []} = props
    return (
        <Select mode={mode}
                placeholder={placeholder}
                showSearch
                defaultValue={defaultValue}
                onChange={onChange}
                notFoundContent={fetching ? <Spin size="small"/> : null}
                filterOption={false}
                onSearch={async x => {
                    await setState({fetching: true})
                    await onSearch(x);
                    await setState({fetching: false})
                }}
                style={{...(style || {}), width: width || '100%'}}
        >
            {(options || []).map(option => <Option key={option.value}>{option.displayValue}</Option>)}
        </Select>
    )
}

const SearchInput = compose(
    withState('state', 'setState', {
        fetching: false
    })
)(_SearchInput)


const FormSearchInput = ({label, getFieldDecorator, required, mode, name, initialValue, rules, onSearch, options = [], placeholder, span, textAlign, labelCol}) => {
    return (
        <Group spans={[span || 16]} textAligns={[textAlign || 'left']}>
            <FormItem
                labelCol={{span: labelCol || 0}}
                wrapperCol={{span: 24 - (labelCol || 0)}}
                label={label}
            >
                {getFieldDecorator(name, {
                    initialValue,
                    rules: [{required, message: '必填项'}],
                })(
                    <SearchInput onSearch={onSearch} options={options} mode={mode} placeholder={placeholder || ''}/>
                )}
            </FormItem>
        </Group>
    )
}
export {SearchInput, FormSearchInput}